package com.reflect.study;

import com.reflect.study.entity.User;

import java.lang.reflect.Field;

/**
 * @author qxf101
 */
public class Test3 {
    public static void main(String[] args) throws Exception {
        Class<?> user = Class.forName("com.reflect.study.entity.User");

        // 获取公共的属性
        Field[] fields = user.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }

        System.out.println("---我是分割线---");

        // 获取所有的属性值
        Field[] fields2 = user.getDeclaredFields();
        for (Field field : fields2) {
            System.out.println(field);
        }

        // 获取public属性值并赋值
        User user1 = (User) user.newInstance();
        Field email = user.getDeclaredField("email");
        email.set(user1, "747070686@qq.com");
        System.out.println(user1.getEmail());

        // 获取private属性并赋值
        User user2 = (User) user.newInstance();
        Field userName = user.getDeclaredField("userName");
        userName.setAccessible(true);
        userName.set(user2,"qxf");
        System.out.println(user2.getUserName());
    }
}
